/*
 ============================================================================
 Name		: GZIPParser.cpp
 Author	  : haoxu
 Version	 : 1.0
 Copyright   : Tencent Research
 Description : CGZIPParser implementation
 ============================================================================
 */

#include "GZIPParser.h"

static const QINT KDefaultBufferSize = 256;

EXPORT_C CGZIPParser::CGZIPParser()
{
	
}

EXPORT_C CGZIPParser::~CGZIPParser()
{
	
}

EXPORT_C void CGZIPParser::BeginL()
{
	User::LeaveIfError(inflateInit(&m_zStream));
}

EXPORT_C void CGZIPParser::SetInput(QPBYTE aSrcBuf, QINT aLength)
{
	m_zStream.next_in = aSrcBuf;
	m_zStream.avail_in = aLength;
}

EXPORT_C QINT CGZIPParser::DecompressL(QPBYTE aDstBuf, QINT aLength)
{
	m_zStream.next_out = aDstBuf;
	m_zStream.avail_out = aLength;
	
	QINT err = inflate(&m_zStream, Z_NO_FLUSH);
	if (err == Z_BUF_ERROR)
	{
		return 0;
	}
	else
	{
		User::LeaveIfError(err);
	}

	return aLength - m_zStream.avail_out;
}

EXPORT_C CQSString CGZIPParser::DecompressL()
{
	CQSString result;
	QPBYTE outBuf = new (ELeave) QBYTE[KDefaultBufferSize];
	CleanupStack::PushL(outBuf);
	QINT length = 0;
	while ((length = DecompressL(outBuf, KDefaultBufferSize)) > 0)
	{
		result.AppendData(outBuf, length);
	}
	CleanupStack::PopAndDestroy(outBuf);
	return result;
}

EXPORT_C void CGZIPParser::EndL()
{
	User::LeaveIfError(inflateEnd(&m_zStream));
}
